/**
 * 扫码点餐功能模块
 */
class QRCodeService {
  constructor() {
    this.qrCodePattern = /^foodorder:\/\/store\/(\d+)(?:\?table=(\d+))?$/
  }

  /**
   * 扫描二维码
   */
  scanQRCode() {
    return new Promise((resolve, reject) => {
      wx.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode'],
        success: (res) => {
          console.log('扫码结果:', res)
          
          // 解析二维码内容
          const parseResult = this.parseQRCode(res.result)
          if (parseResult.success) {
            resolve(parseResult)
          } else {
            reject(new Error(parseResult.message))
          }
        },
        fail: (error) => {
          console.error('扫码失败:', error)
          if (error.errMsg.includes('cancel')) {
            reject(new Error('用户取消扫码'))
          } else {
            reject(new Error('扫码失败，请重试'))
          }
        }
      })
    })
  }

  /**
   * 解析二维码内容
   */
  parseQRCode(qrContent) {
    try {
      // 检查是否是餐饮点餐系统的二维码
      const match = qrContent.match(this.qrCodePattern)
      
      if (match) {
        const storeId = parseInt(match[1])
        const tableNumber = match[2] ? parseInt(match[2]) : null
        
        return {
          success: true,
          type: 'store',
          storeId,
          tableNumber,
          orderType: 'dine_in'
        }
      }
      
      // 检查是否是网址格式的二维码
      if (qrContent.startsWith('http')) {
        const url = new URL(qrContent)
        const pathMatch = url.pathname.match(/\/store\/(\d+)/)
        
        if (pathMatch) {
          const storeId = parseInt(pathMatch[1])
          const tableNumber = url.searchParams.get('table')
          
          return {
            success: true,
            type: 'store',
            storeId,
            tableNumber: tableNumber ? parseInt(tableNumber) : null,
            orderType: 'dine_in'
          }
        }
      }
      
      return {
        success: false,
        message: '无效的二维码，请扫描店铺点餐二维码'
      }
      
    } catch (error) {
      console.error('解析二维码失败:', error)
      return {
        success: false,
        message: '二维码格式错误'
      }
    }
  }

  /**
   * 处理扫码结果
   */
  async handleScanResult(scanResult) {
    try {
      if (scanResult.type === 'store') {
        // 跳转到店铺详情页，设置为店内点餐模式
        const url = `/pages/store-detail/store-detail?id=${scanResult.storeId}&orderType=dine_in`
        
        if (scanResult.tableNumber) {
          // 如果有桌号，保存到全局数据
          const app = getApp()
          app.globalData.currentTable = {
            storeId: scanResult.storeId,
            tableNumber: scanResult.tableNumber
          }
          
          wx.showToast({
            title: `已扫描桌号：${scanResult.tableNumber}`,
            icon: 'success'
          })
        }
        
        wx.navigateTo({
          url: url,
          success: () => {
            wx.showToast({
              title: '进入店内点餐模式',
              icon: 'success'
            })
          }
        })
        
        return true
      }
      
      return false
      
    } catch (error) {
      console.error('处理扫码结果失败:', error)
      wx.showToast({
        title: '处理失败，请重试',
        icon: 'none'
      })
      return false
    }
  }

  /**
   * 生成店铺二维码（用于商家端）
   */
  generateStoreQRCode(storeId, tableNumber = null) {
    let qrContent = `foodorder://store/${storeId}`
    if (tableNumber) {
      qrContent += `?table=${tableNumber}`
    }
    return qrContent
  }

  /**
   * 验证桌号
   */
  validateTableNumber(tableNumber) {
    if (!tableNumber) return false
    
    const num = parseInt(tableNumber)
    return !isNaN(num) && num > 0 && num <= 999
  }

  /**
   * 获取当前桌号信息
   */
  getCurrentTableInfo() {
    const app = getApp()
    return app.globalData.currentTable || null
  }

  /**
   * 清除桌号信息
   */
  clearTableInfo() {
    const app = getApp()
    app.globalData.currentTable = null
  }

  /**
   * 显示扫码引导
   */
  showScanGuide() {
    wx.showModal({
      title: '扫码点餐',
      content: '请扫描桌上的二维码开始点餐\n\n• 对准二维码\n• 保持稳定\n• 确保光线充足',
      confirmText: '开始扫码',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.scanQRCode()
            .then(result => this.handleScanResult(result))
            .catch(error => {
              wx.showToast({
                title: error.message,
                icon: 'none'
              })
            })
        }
      }
    })
  }

  /**
   * 检查扫码权限
   */
  checkScanPermission() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.camera'] === false) {
            // 用户拒绝了相机权限
            wx.showModal({
              title: '需要相机权限',
              content: '扫码功能需要使用相机，请在设置中开启相机权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success: (settingRes) => {
                      if (settingRes.authSetting['scope.camera']) {
                        resolve(true)
                      } else {
                        reject(new Error('未开启相机权限'))
                      }
                    }
                  })
                } else {
                  reject(new Error('需要相机权限才能扫码'))
                }
              }
            })
          } else {
            // 有权限或未询问过
            resolve(true)
          }
        },
        fail: () => {
          reject(new Error('获取权限信息失败'))
        }
      })
    })
  }

  /**
   * 安全扫码（包含权限检查）
   */
  async safeScanQRCode() {
    try {
      await this.checkScanPermission()
      const result = await this.scanQRCode()
      return await this.handleScanResult(result)
    } catch (error) {
      wx.showToast({
        title: error.message,
        icon: 'none'
      })
      return false
    }
  }
}

// 创建实例
const qrCodeService = new QRCodeService()

module.exports = qrCodeService 